package cn.kgm.loop;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @Version 1.8
 * @Author: Kappi
 * @Date: 2025-7-31 17:22
 * @Description: cn.kgm.loop.LoopTest
 */
public class LoopTest {

    public static void main(String[] args) {
        HashMap<String, List<String>> a = new HashMap<>();
        a.put("a", Arrays.asList("b", "c"));
        HashMap<String, List<String>> b = new HashMap<>();
        b.put("b", Arrays.asList("a", "d"));
        HashMap<String, List<String>> c = new HashMap<>();
        c.put("c", Arrays.asList("a", "d"));
        HashMap<String, List<String>> d = new HashMap<>();
        d.put("d", Arrays.asList("b", "c"));
        List<HashMap<String, List<String>>> arr = Arrays.asList(a, b, c, d);
        // 拿到"a"
        String mainKey = arr.get(0).keySet().toArray()[0].toString();
        // 拿到a的连接位置,在除了这两点之外的他们的相关连接里找"a" 找到了说明有中断连接的循环
        List<HashMap<String, List<String>>> hashMaps = find(arr, mainKey, mainKey, new ArrayList<>());
    }

    /**
     * @param arr     全部数据
     * @param mainKey 主key
     * @param mainRef 主key的关联类
     * @return
     */
    private static List<HashMap<String, List<String>>> find(List<HashMap<String, List<String>>> arr, String cuKey, String mainKey, List<HashMap<String, List<String>>> mainRef) {
        if (mainRef.isEmpty()) {
            arr.removeAll(mainRef);
        }
        List<HashMap<String, List<String>>> copy = new ArrayList<>();
        for (HashMap<String, List<String>> map : arr) {
            for (List<String> value : map.values()) {
                if (value.contains(mainKey)) {
                    copy.add(map);
                }
            }
        }
        //此时copy李
        if (copy.size() != 0 && mainRef.isEmpty()) {
            for (HashMap<String, List<String>> map : copy) {
                find(arr, map.keySet().toArray()[0].toString(), mainKey, copy);
            }
        }

        return copy;
    }
}
